package io.github.zatter.qiniucorejava.service;

import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import io.github.zatter.qiniucorejava.utils.TextToVoiceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * {@code @Author: soyo}
 * {@code @Description: }
 * {@code @Create: 2025/9/23}
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AiChatService {
    private final StreamingChatLanguageModel streamingChatLanguageModel;
    private final TextToVoiceService textToVoiceService;

    public void askAndSpeak(String question) {
        streamingChatLanguageModel.chat(
                question,
                new StreamingChatResponseHandler() {
                    private StringBuilder buffer = new StringBuilder();

                    @Override
                    public void onPartialResponse(String s) {
                        System.out.print(s); // 控制台实时打印
                        buffer.append(s);

                        // 简单分句规则：检测句子结束符
                        if (buffer.toString().matches(".*[。！？.!?]\\s*$")) {
                            String sentence = buffer.toString();
                            buffer.setLength(0);

                            // 异步执行 TTS，避免阻塞 LLM 流式输出
                            CompletableFuture.runAsync(() -> {
                                byte[] audio = fakeTtsService(sentence);
                            });
                        }
                    }

                    @Override
                    public void onCompleteResponse(ChatResponse chatResponse) {
                        System.out.println("\n回答结束 ✅");

                        // 处理未播出的尾巴
                        if (buffer.length() > 0) {
                            String lastSentence = buffer.toString();
                            buffer.setLength(0);

                            CompletableFuture.runAsync(() -> {
                                byte[] audio = fakeTtsService(lastSentence);
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable throwable) {
                        System.out.println("\n回答错误 ❌: " + throwable.getMessage());
                    }
                }
        );
    }

    // 模拟 TTS 服务
    private byte[] fakeTtsService(String text) {
        System.out.println("\n[TTS] 生成语音：" + text);
        return textToVoiceService.textToSpeech(text);
    }

}
